package ccm.component.input;

import ccm.common.Configurable;
import ccm.common.ReceiveDataListener;
import ccm.common.StatusChangeListener;
import ccm.common.TooManyListenerException;

import javax.swing.*;
import java.awt.event.ActionListener;

abstract public class InputJPanel extends JPanel implements Configurable, ActionListener
{
    /**
     * 状态改变的监听器
     */
    protected StatusChangeListener statusChangeListener;
    /**
     * 接收数据的监听器
     */
    protected ReceiveDataListener  receiveDataListener;
    /**
     * 追加的结尾的下拉菜单
     */
    protected JComboBox<String>    endJComboBox;

    InputJPanel()
    {
        super();
        /*
           生成追加的结尾的下拉菜单
         */
        endJComboBox=new JComboBox<>(new String[]{"\r\n","\r","\n",""});
        endJComboBox.setSelectedIndex(0);
        add(endJComboBox);
        endJComboBox.addActionListener(this);
        endJComboBox.setRenderer((list,value,index,isSelected,cellHasFocus)->{
            JLabel jLabel=new JLabel(" "+value.replace("\r","\\r").replace("\n","\\n"));
            jLabel.setOpaque(true);
            return jLabel;
        });
    }

    /**
     * 获取追加的结尾
     *
     * @return 一个字符串表示追加的结尾
     */
    protected String getEndString()
    {
        return (String)endJComboBox.getSelectedItem();
    }

    /**
     * 添加一个接收数据监听器
     *
     * @param listener 监听器
     * @throws TooManyListenerException 监听器过多时抛出此异常
     * @throws NullPointerException     监听器为null时抛出此异常
     * @implNote 默认添加到通道0
     * 只支持一个监听器
     */
    public void addDataReceiveListener(ReceiveDataListener listener) throws TooManyListenerException, NullPointerException
    {
        addDataReceiveListener(listener,0);
    }

    /**
     * 添加一个接收数据监听器
     *
     * @param listener 监听器
     * @param channel  通道
     * @throws TooManyListenerException 监听器过多时抛出此异常
     * @throws NullPointerException     监听器为null时抛出此异常
     * @implNote 只支持一个监听器
     */
    public void addDataReceiveListener(ReceiveDataListener listener,int channel) throws TooManyListenerException, NullPointerException
    {
        if(listener==null)
            throw new NullPointerException();
        if(receiveDataListener!=null||channel<0)
            throw new TooManyListenerException();
        receiveDataListener=listener;
    }

    /**
     * 添加状态变化监听器
     *
     * @param listener 监听器
     * @throws TooManyListenerException 监听器过多时抛出此异常
     * @throws NullPointerException     监听器为null时抛出此异常
     * @implNote 只支持一个监听器
     */
    public void addStatusChangeListener(StatusChangeListener listener) throws TooManyListenerException, NullPointerException
    {
        if(listener==null)
            throw new NullPointerException();
        if(statusChangeListener!=null)
            throw new TooManyListenerException();
        statusChangeListener=listener;
    }
}
